package com.ls.db.pg;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BinaryData {

	public static void main(String[] args) {
		String driver = "org.postgresql.Driver";
        String url = "jdbc:postgresql://" + "20.12.16.182" + ":" + "5432" + "/" + "soma";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet st = null;
        try {
             Class.forName(driver);
             System.out.println("success find class");
             conn = DriverManager.getConnection(url, "liblc", "ufsoft");
             System.out.println("success connect"); 
             
             insertBytes(conn);
             getBytes(conn);
	}catch(Exception e){
		e.printStackTrace();
	}finally{
		if(conn!=null)
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	}

	private static void insertBytes(Connection conn) throws SQLException {
		PreparedStatement ps;
		ps = conn.prepareStatement("INSERT INTO images VALUES (?, ?)");
		 ps.setString(1, "a");
		 ps.setBytes(2, "cc".getBytes());
		 ps.executeUpdate();
		 ps.close();
	}
	
	private static void getBytes(Connection conn)throws SQLException{
		PreparedStatement ps = conn.prepareStatement("SELECT img FROM images WHERE imgname = ?");
		ps.setString(1, "a");
		ResultSet rs = ps.executeQuery();
		while (rs.next())
		{
		   byte[] imgBytes = rs.getBytes(1);
		  System.out.println(new String(imgBytes));
		}
		rs.close();
		ps.close();
	}
}
